#include "scanlyric.h"

ScanLyric::ScanLyric(QObject *parent, \
                     const QString &musicname, const QString &path) : QObject(parent)
{
    //歌曲名称:name.mp3 -> name
    QString songName = musicname.left(musicname.lastIndexOf('.'));
    this->setMusicName(songName);
    QString fullPath = path;
    QDir dir(fullPath);
    QString directoryPath = dir.absolutePath();
    QStringList parts = directoryPath.split('/');
    if (!parts.isEmpty()){
        QString firstDirectory = parts[0];
        if (parts.size() > 1) {
            firstDirectory = parts[1];
            this->setStartPath(firstDirectory);
        }
    }
    finLrcFiles("/"+this->getStartPath());
}

void ScanLyric::finLrcFiles(const QString &path)
{
    QDir dir(path);
    if (!dir.exists()) {
        qDebug() << "Dir" << path << "does not exist!";
        return;
    }

    QFileInfoList entries = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QFileInfo &entry : entries) {
        if (entry.isFile()) {
            QString fileName = entry.fileName();
            QString suffix = entry.suffix().toLower();
            if (suffix == "lrc") {
                // 提取歌词文件名（去掉.lrc后缀）
                QString lrcNameWithoutSuffix = fileName.left(fileName.lastIndexOf('.'));
                // 检查是否匹配歌曲名
                if (lrcNameWithoutSuffix == this->getMusicName()) {
                    this->setLrcName(fileName);
                    this->setLrcAbsolutePath(entry.absoluteFilePath());
                    return; // 找到后直接返回
                }
            }
        } else if (entry.isDir()) {
            finLrcFiles(entry.absoluteFilePath());
        }
    }
}

QString ScanLyric::getLrcAbsolutePath() const
{
    return lrcAbsolutePath;
}

void ScanLyric::setLrcAbsolutePath(const QString &value)
{
    lrcAbsolutePath = value;
}

QString ScanLyric::getLrcName() const
{
    return lrcName;
}

void ScanLyric::setLrcName(const QString &value)
{
    lrcName = value;
}

QString ScanLyric::getStartPath() const
{
    return startPath;
}

void ScanLyric::setStartPath(const QString &value)
{
    startPath = value;
}

QString ScanLyric::getMusicName() const
{
    return musicName;
}

void ScanLyric::setMusicName(const QString &value)
{
    musicName = value;
}
